package edu.office.tools;
/*
向客户端expose的只有账号和密码，而用户的姓和名则从在这个类中存储
valid用于表示登录是否成功，如果成功，则firstName和seconName不是空字符串，可以向客户expose，用于在页面上显示
 */

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class UserWithName {
    private int roleId;
    private String name;

    private boolean valid=false;
    private String firstName;
    private String secondName;

    public boolean isValid() {
        return valid;
    }

    public void setValid(boolean valid) {
        this.valid = valid;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getSecondName() {
        return secondName;
    }

    public void setSecondName(String secondName) {
        this.secondName = secondName;
    }

    public int getRoleId() {
        return roleId;
    }

    public void setRoleId(int roleId) {
        this.roleId = roleId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getHashValue(){
        return computeHash(this.roleId +this.name+this.secondName+this.firstName);
    }

    public String computeHash(String input) {
        //计算输入的哈希值，这段值与原值一起传输，用于检测是否被篡改
        try {
            // 创建一个SHA-256 MessageDigest实例
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            // 将输入字符串转换为字节数组，并更新摘要
            md.update(input.getBytes(StandardCharsets.UTF_8));
            // 计算哈希值并转换为十六进制字符串
            byte[] hashBytes = md.digest();
            StringBuilder hexString = new StringBuilder();
            for (byte b : hashBytes) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA-256哈希算法不可用", e);
        }
    }
}
